package article_api

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
)

// FullTextSearch 全文搜索接口
// @Summary 全文搜索
// @Description 根据关键字进行全文搜索
// @Tags 文章管理
// @Accept json
// @Produce json
// @Param key query string false "关键字"
// @Security ApiKeyAuth
// @Success 200 {object} res.Response{}
// @Failure 400 {object} res.Response "参数错误"
// @Failure 401 {object} res.Response "未授权访问"
// @Failure 500 {object} res.Response "内部服务器错误"
// @Router /api/articles/full_search [get]
func (ArticleApi) FullTextSearch(c *gin.Context) {
	var cr models.PageInfo
	_ = c.ShouldBindQuery(&cr)
	boolQuery := elastic.NewBoolQuery()
	if cr.Key != "" {
		boolQuery.Must(elastic.NewMultiMatchQuery(cr.Key, "title", "body"))
	}
	result, err := global.EsClient.
		Search(models.FullTextModel{}.Index()).
		Query(boolQuery).
		Highlight(elastic.NewHighlight().Field("body")). //文章高亮搜索
		Size(1000).
		Do(context.Background())

	if err != nil {
		return
	}
	//统计索引个数
	count := result.Hits.TotalHits.Value
	demoList := make([]models.FullTextModel, 0)
	for _, hit := range result.Hits.Hits {
		var demo models.FullTextModel
		_ = json.Unmarshal(hit.Source, &demo)
		body, ok := hit.Highlight["body"]
		if ok {
			demo.Body = body[0]
		}
		demoList = append(demoList, demo)
	}
	res.OkWithList(demoList, count, c)
}
